<?php
/**
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 * 
 * @author Eddie Drapkin <eddie@frameweld.com>
 * @license http://www.gnu.org/licenses/lgpl-3.0.txt
 * @package Solphr
 * @version 0.1-pre
 */

/**
 * Solphr_Record class used to represent a record to index for Solphr_AddUpdate.
 * @author Eddie Drapkin <eddie@frameweld.com>
 * @license http://www.gnu.org/licenses/lgpl-3.0.txt
 * @package Solphr
 */
class Solphr_Record {
	private $fields;
	private $boost = false;
	
	public function __construct(array $fields = array()) {
		$this->fields = $fields;
	}
	
	public function setField($field, $value) {
		$this->__set($field, $value);
	}
	
	public function __set($field, $value) {
		if(!isset($this->fields[$field])) {
			$this->fields[$field] = $value;
		} else {
			$this->fields[$field] = array(
				'values' => array(
					$this->fields[$field],
					$value
				)
			);
		}
	}
	
	
	public function getField($field) {
		return $this->__get($field);
	}
	
	public function __get($field) {
		return $this->fields[$field];
	}
	
	public function __toString() {
		if(empty($this->fields)) {
			return '';
		}
		
		return $this->toXML();
	}
	
	public function setBoost($value) {
		$this->boost = (int)$value;
	}
	
	public function setFieldBoost($field, $value) {
		if(!isset($this->fields[$field])) {
			$this->fields[$field] = array( 
				'boost' => $value
			);
		} else {
			$this->fields[$field] = array(
				'boost' => $value,
				'values' => array(
					$this->fields[$field]
				)
			);
		}
	}
	
	private function toXML() {
		$xml = '<doc';
		if($this->boost !== false) {
			$xml .= " boost=\"{$this->boost}\"";
		}
		$xml .= '>';
		
		foreach($this->fields as $key => $field) {
			if(!is_array($field)) {
				$xml .= "<field name=\"$key\">$field</field>";
			} else {
				if(!isset($field['values'])) {
					throw new Solphr_Exception("Unexpected structure of field {$field} with name {$key}.  Most likely this means you set a boost without specifying a field value.");
				}
				
				$boost = isset($field['boost']) ? " boost=\"{$field['boost']}" : '';
				
				foreach($field['values'] as $f) {
					$xml .= "<field name=\"$key\"{$boost}>$f</field>";
				}
			}
			
		}
		
		$xml .= '</doc>';
		
		return $xml;
	}
}